import express from 'express'
import isEmpty from 'lodash/isEmpty'
import validator from 'validator'
import bcrypt from 'bcrypt'

import User from '../models/user'

let router = express.Router()

const commonValidateInput = data => {
    let errors = {}
    if(validator.isEmpty(data.username)){
        errors.username = 'The field is required'
    }

    if (validator.isEmpty(data.email)) {
        errors.email = 'The field is required'
    }

    if (!validator.isEmail(data.email)) {
        errors.email = 'Email is valid'
    }

    if (validator.isEmpty(data.password)) {
        errors.password = 'The field is required'
    }

    if (validator.isEmpty(data.passwordConfirmation)) {
        errors.passwordConfirmation = 'The field is required'
    }


    if(!validator.equals(data.password, data.passwordConfirmation)){
        errors.passwordConfirmation = 'Password must match.'
    }

    return {
        errors,
        isValid: isEmpty(errors)
    }
}

const validateInput = (data, otherValidateInput) => {
    let { errors } = otherValidateInput(data)

    return User.query({
                where: { email: data.email },
                orWhere: { username: data.username }
            }).fetch().then(user => {
                if(user){
                    if(user.get('email') === data.email){
                        errors.email = 'There is user with such email'
                    }
                    if(user.get('username') === data.username){
                        errors.username = 'There is user with such username'
                    }
                }

                return {
                    errors,
                    isValid: isEmpty(errors)
                }
            })
}

router.get('/:user',(req, res) => {
    console.log(req.params)
    User.query({
        select:["username", "email"],
        where:{ email: req.params.user},
        orWhere:{ username: req.params.user}
    }).fetch().then(user => {
        res.json({ user })
    })
})

router.post('/', (req, res) => {
    validateInput(req.body, commonValidateInput)
    .then(({errors, isValid}) => {

        if (!isValid) {
            res.status(400).json(errors)
        }else{
            const { username, password, email } = req.body
            const password_digest = bcrypt.hashSync(password, 10)

            User.forge({
                username, password_digest, email
            },{ hasTimeStamps: true }).save()
            .then(user => res.json({success:true}))
            .catch(err => res.status(500).json({ errors: err }))
            //res.status(200).json({msg:'success'})
        }
    })
    
})

export default router